import {
  getProPrivilegeReq,
  getUserPrivilegeReq
} from '@/service/modules/data-manage'
import {
  ProTablePrivilege,
  UserTablePrivilege
} from '@/service/modules/data-manage/types'
import { reactive } from 'vue'

export function useTablePrivilege() {
  const state = reactive({
    page: 1,
    limit: 10,
    count: 0,
    datasourceId: 0,
    dbName: '',
    tableName: '',
    proName: '',
    loading: false,
    userPrivilegeList: [],
    proPrivilegeList: [],
    currentRecord: {} as ProTablePrivilege | UserTablePrivilege,
    modUserPrivilegeModalShow: false,
    modProPrivilegeModalShow: false
  })

  const getUserPrivilege = async () => {
    if (state.loading) return
    state.loading = true
    const res = await getUserPrivilegeReq({
      datasourceId: state.datasourceId,
      dbName: state.dbName,
      tableName: state.tableName
    })
    state.loading = false
    if (res.resp_code === 0) {
      state.userPrivilegeList = res.data
    }
  }
  const getProPrivilege = async () => {
    if (state.loading) return
    state.loading = true
    const res = await getProPrivilegeReq({
      page: state.page,
      limit: state.limit,
      datasourceId: state.datasourceId,
      dbName: state.dbName,
      tableName: state.tableName,
      proName: state.proName
    })
    state.loading = false
    if (res.resp_code === 0) {
      state.proPrivilegeList = res.data
    }
  }

  const onOperationClick = (
    data: { rowData: UserTablePrivilege | ProTablePrivilege },
    type: 'modUserPrivilege' | 'modProPrivilege'
  ) => {
    state.currentRecord = data.rowData
    switch (type) {
      case 'modUserPrivilege':
        state.modUserPrivilegeModalShow = true
        break
      case 'modProPrivilege':
        state.modProPrivilegeModalShow = true
        break
    }
  }

  const changePage = (page: number) => {
    state.page = page
    getProPrivilege()
  }

  const changePageSize = (limit: number) => {
    state.page = 1
    state.limit = limit
    getProPrivilege()
  }
  return {
    state,
    getUserPrivilege,
    getProPrivilege,
    changePage,
    changePageSize,
    onOperationClick
  }
}
